package com.example.resourceSharingPlatform.security_service.impl;

import com.example.resourceSharingPlatform.security_entity.Users;
import com.example.resourceSharingPlatform.security_service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 通过username填充UserDetails实体
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UsersService usersService;
    /*
     * loadUserByUsername(String username)
     * 通过用户名获取对应的userDetails实体
     * 这个函数会从数据库中获取username对应的数据
     * 并且把由逗号分隔的权限字符串解析成权限集（权限对象列表）
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws
            UsernameNotFoundException {
        Users users = usersService.selectUserByUserName(username);
        if (users == null) {
            throw new UsernameNotFoundException("登录用户：" + username + "不存在");
        }
        //将数据库的roles解析为UserDetails的权限集
        //AuthorityUtils.commaSeparatedStringToAuthorityList将逗号分隔的字符集转成权限对象列表
        users.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(users.getRoles()));
        return users;
    }
}



